package store.dao;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

@Repository
public abstract class AbstractDao<T extends Serializable> implements IDao<T> {

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;
    private Class<T> classType;

    protected AbstractDao() {
    }

    protected AbstractDao(Class<T> classType) {
        this.classType = classType;
    }

    @Override
    public void create(T entity) {
        sessionFactory.getCurrentSession().save(entity);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T read(Integer id) {
        return (T) sessionFactory.getCurrentSession().get(classType, id);
    }

    @Override
    public void update(T entity) {
        sessionFactory.getCurrentSession().update(entity);
    }

    @Override
    public void delete(T entity) {
        sessionFactory.getCurrentSession().delete(entity);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> readAll() {
        List<T> temp = sessionFactory.getCurrentSession().createCriteria(classType).list();
        return temp;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T findByField(String fieldName, Object value) {
        Criteria cr = sessionFactory.getCurrentSession().createCriteria(classType);
        return (T) cr.add(Restrictions.eq(fieldName, value)).uniqueResult();

    }
}
